package com.like.hospitalworld;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.like.entity.CheckMobileKeyReq;
import com.like.entity.CheckMobileKeyResp;
import com.like.entity.GeneralResponse;
import com.like.entity.MobileKeyReq;
import com.like.entity.MobileKeyResp;
import com.like.entity.RegReq;
import com.like.entity.RegResp;
import com.like.likeutils.network.RetrofitCallback;
import com.like.likeutils.util.TimeCount;
import com.like.network.AuthService;
import com.like.network.ResponseCode;
import com.like.network.RetrofitUtil;
import com.like.utils.AppUtils;
import com.like.utils.Constants;
import com.like.widget.MyToast;
import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.mobsandgeeks.saripaar.annotation.Order;
import com.mobsandgeeks.saripaar.annotation.Pattern;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

import retrofit2.Call;
import retrofit2.Response;

@ContentView(R.layout.activity_reg)
public class RegActivity extends BaseActivity implements TimeCount.TimeListener, Validator.ValidationListener {

    public static final int VALIDATE_ALL = 0;
    public static final int VALIDATE_MP = 1;

    @ViewInject(R.id.mobile_no)
    @Pattern(regex = "^[1][0-9]{10}$", message = "手机号码格式错误")
    @Order(0)
    private EditText mMobileNo;
    @ViewInject(R.id.mobile_key)
    @NotEmpty(message = "请输入验证码")
    @Order(1)
    private EditText mMobileKey;
    @ViewInject(R.id.pwd)
    @NotEmpty(message = "请输入密码")
    @Order(2)
    private EditText mPwd;
    @ViewInject(R.id.check_agree)
    private CheckBox mCheckAgree;
    @ViewInject(R.id.get_mobile_key)
    private Button mBtnMobileKey;

    private AuthService mAuthService;
    private Validator mValidator;
    private boolean mIsAllPass = false;
    private boolean mIsMpPass = false;
    private int mCurrentValidate = VALIDATE_MP;
    private TimeCount mCountDown = new TimeCount(50000, 1000, this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAuthService = RetrofitUtil.getService(AuthService.class);
        mValidator = new Validator(this);
        mValidator.setValidationListener(this);
    }

    @Event(R.id.back)
    private void backClick(View v) {
        finish();
    }

    @Event(R.id.get_mobile_key)
    private void mobileKeyClick(View v) {
        mCurrentValidate = VALIDATE_MP;
        mValidator.validate();
        System.out.println(mIsMpPass);
        if (!mIsMpPass)
            return;
        String mobile = mMobileNo.getText().toString();
        MobileKeyReq req = new MobileKeyReq(mobile, "1");
        Call<GeneralResponse<MobileKeyResp>> call = mAuthService.getMobileKey(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<MobileKeyResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<MobileKeyResp>> call, Response<GeneralResponse<MobileKeyResp>> response) {
                if (!response.isSuccessful())
                    return;
                MobileKeyResp resp = response.body().data;
                if (resp.result == ResponseCode.SUCCESS) {
                    mBtnMobileKey.setEnabled(false);
                    mBtnMobileKey.setText("验证码已发送");
                }
            }
        });
        mCountDown.start();
    }

    @Event(R.id.reg)
    private void regClick(View v) {
        mCurrentValidate = VALIDATE_ALL;
        if (!mCheckAgree.isChecked()) {
            MyToast.showBlueCircleToast(m.mContext, "请同意声明");
            return;
        }
        mValidator.validate();
        if (!mIsAllPass)
            return;
        String mobile = mMobileNo.getText().toString();
        String key = mMobileKey.getText().toString();
        String pwd = mPwd.getText().toString();
        checkMobileKey(mobile, key, pwd);
    }

    private void checkMobileKey(final String mobile, String key, final String pwd) {
        CheckMobileKeyReq req = new CheckMobileKeyReq(mobile, key, 1);
        Call<GeneralResponse<CheckMobileKeyResp>> call = mAuthService.checkMobileKey(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<CheckMobileKeyResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<CheckMobileKeyResp>> call, Response<GeneralResponse<CheckMobileKeyResp>> response) {
                if (!response.isSuccessful())
                    return;
                GeneralResponse resp = response.body();
                if (resp.result == 1)
                    reg(mobile, pwd);
                else
                    MyToast.showBlueCircleToast(m.mContext, "验证码错误");
            }
        });
    }

    private void reg(String mobile, String pwd) {
        RegReq req = new RegReq(mobile, AppUtils.getDeviceId(m.mContext), pwd, m.getLatitude() + "#" + m.getLongitude());
        Call<GeneralResponse<RegResp>> call = mAuthService.reg(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<RegResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<RegResp>> call, Response<GeneralResponse<RegResp>> response) {
                if (!response.isSuccessful())
                    return;
                GeneralResponse resp = response.body();
                if (resp.result == ResponseCode.SUCCESS) {
                    MyToast.showBlueCircleToast(m.mContext, "注册成功");
                    Intent intent = new Intent(m.mContext, LoginActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    MyToast.showBlueCircleToast(m.mContext, "注册失败");
                }
            }
        });
    }

    @Override
    public void onTick(long millisUntilFinished) {
        long sec = millisUntilFinished / 1000;
        mBtnMobileKey.setText(sec + "秒后重发");
    }

    @Override
    public void onFinish() {
        mBtnMobileKey.setEnabled(true);
        mBtnMobileKey.setText("获取验证码");
    }

    @Override
    public void onValidationSucceeded() {
        mIsAllPass = true;
        mIsMpPass = true;
    }

    @Override
    public void onValidationFailed(List<ValidationError> errors) {
        mIsAllPass = false;
        if (mCurrentValidate == VALIDATE_MP) {
            for (ValidationError error : errors) {
                if (error.getView().getId() == R.id.mobile_no) {
                    String msg = error.getCollatedErrorMessage(m.mContext);
                    MyToast.showBlueCircleToast(m.mContext, msg);
                    mIsMpPass = false;
                    return;
                }
            }
            mIsMpPass = true;
        } else if (mCurrentValidate == VALIDATE_ALL) {
            String msg = errors.get(0).getCollatedErrorMessage(m.mContext);
            MyToast.showBlueCircleToast(m.mContext, msg);
        }
    }
}
